<template>
  <div>
<van-cell v-for='item in suggestions' :key='item ' @click="onSearch(item)"  >
  <template>
    <van-icon name="close" />
  </template>
  <template #title>
    <p v-html='heigthText(item)'></p>
  </template>
</van-cell>

  </div>
</template>

<script>
import { getAllChannels } from '@/api/search.js'
export default {
  props: {
    searchText: {
      type: String,
      require: true
    }
  },
  data () {
    return {
      suggestions: []
    }
  },

  created () {

  },

  methods: {
    // 高亮搜索
    heigthText (item) {
      const resplaceStr = '<span style="color: red">' + this.searchText + '</span>'
      // 动态正则
      const reg = new RegExp(this.searchText, 'gi')
      return item.replace(reg, resplaceStr)
    },
    // 点击搜素
    onSearch (item) {
      console.log(item)
      this.$emit('onsearch', item)
    }

  },
  // 当searchText内容为空时 该组件就会被销毁 在即将销毁的时候在清除定时器 表示在销毁前不在发请求
  beforeDestroy () {
    clearTimeout(this.setid)
  },
  watch: {
    searchText: {
      immediate: true,
      handler (val) {
        if (this.setid) clearTimeout(this.setid)
        this.setid = setTimeout(async () => {
          const res = await getAllChannels(this.searchText)
          this.suggestions = res.options
          console.log(res)
        }, 700)
      }
    }
  }
}
</script>

<style scoped lang='less'>

</style>
